package validate

import (
	"errors"
	"fmt"
	"slices"
	"strconv"
	"strings"

	"github.com/mitchellh/mapstructure"

	"github.com/go-playground/validator/v10"
)

type ValidateParams struct {
	validate *validator.Validate
}

func NewValidateParams() *ValidateParams {
	validateParams := &ValidateParams{
		validate: validator.New(),
	}
	validateParams.validate.RegisterValidation("checkPhoneAndEmail", checkPhoneAndEmail)
	return validateParams
}

// 单个参数验证
func (v *ValidateParams) CheckParams(param any, validateRule string) error {
	err := v.validate.Var(param, validateRule)
	if err != nil {
		return err
	}
	return nil
}

// 结构体参数验证
func (v *ValidateParams) CheckStructParams(postMap map[string][]string, paramTypeMap map[string][]string, validateStruct any) error {
	if len(postMap) == 0 {
		return errors.New("参数无效")
	}
	postDataMap := map[string]any{}
	for k, v := range postMap {
		if v == nil {
			continue
		}

		// 检测并处理多值参数
		if strings.HasSuffix(k, "[]") {
			key := strings.TrimSuffix(k, "[]") // 移除 "[]"
			postDataMap[key] = v               // 如果是多值参数，直接将整个切片赋值
		} else {
			if _, exists := paramTypeMap["int"]; exists && slices.Contains(paramTypeMap["int"], k) {
				// 参数转int
				if len(v) > 0 {
					if intValue, err := strconv.Atoi(v[0]); err == nil {
						postDataMap[k] = intValue
					}
				}
			} else if _, exists := paramTypeMap["float"]; exists && slices.Contains(paramTypeMap["float"], k) {
				// 参数转float
				if len(v) > 0 {
					if floatValue, err := strconv.ParseFloat(v[0], 64); err == nil {
						postDataMap[k] = floatValue
					}
				}
			} else {
				// 默认为字符串
				postDataMap[k] = v[0]
			}
		}
	}

	err := mapstructure.Decode(postDataMap, &validateStruct)
	if err != nil {
		fmt.Println("errerrerrerr", err)
		return errors.New("参数错误")
	}
	err = v.validate.Struct(validateStruct)
	if err != nil {
		if _, ok := err.(*validator.InvalidValidationError); ok {
			return errors.New("InvalidValidationError,无效验证错误")
		}
		return errors.New(err.(validator.ValidationErrors)[0].Field() + "参数错误")
	}
	return nil
}
